const express = require('express');
const router = express.Router();
const Product = require('../../models/product');

// 获取产品列表
router.post('/list', async (req, res) => {
  try {
    const { page = 1, limit = 10, category, brand, keyword } = req.body;
    const query = {};

    if (category) query.category = category;
    if (brand) query.brand = brand;
    if (keyword) {
      query.$or = [
        { name: { $regex: keyword, $options: 'i' } },
        { description: { $regex: keyword, $options: 'i' } }
      ];
    }

    const total = await Product.countDocuments(query);
    const products = await Product.find(query)
      .populate('category')
      .populate('brand')
      .skip((page - 1) * limit)
      .limit(Number(limit))
      .sort({ createdAt: -1 });

    res.status(200).json({
      code: 200,
      data: {
        list: products,
        pagination: {
          total,
          page: Number(page),
          limit: Number(limit)
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: error.message
    });
  }
});

// 获取产品详情
router.get('/:id', async (req, res) => {
  try {
    const product = await Product.findById(req.params.id)
      .populate('category')
      .populate('brand');

    if (!product) {
      return res.status(404).json({
        code: 404,
        message: '产品不存在'
      });
    }

    res.status(200).json({
      code: 200,
      data: product
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: error.message
    });
  }
});

module.exports = router; 